package com.zx.deploy;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.zx.deploy.common.utils.HttpClientUtil;
import com.zx.deploy.service.PackageService;
import com.zx.deploy.service.impl.Md5PackageServiceImpl;

public class PackageApplication {

	private static  Logger logger  =  Logger.getLogger(PackageApplication.class);
	
	public static void main(String[] args) {
	    try {
		     //读取第一个参数,0:只打包不上传 1：先打包再上传	
		     String cmdFlag=(args!=null&&args.length>0)?args[0]:null;
			 String soft_unzip_name="update_package";
			 String soft_package_name="update_package.zip";
			 PackageService packageService = new Md5PackageServiceImpl();
			 Properties properties = new Properties();
		     // 使用ClassLoader加载properties配置文件生成对应的输入流
		     String propertiesPath=PackageApplication.class.getClassLoader().getResource("").getPath()+"package.properties";
		     InputStream in = new FileInputStream(new File(propertiesPath));
		     // 使用properties对象加载输入流
			 properties.load(in);
			 logger.info("======开始进行打包======");
			 //1、压缩文件夹
			 packageService.setPackage(soft_unzip_name,soft_package_name);
			 //2、写入文件头信息
			 String package_path=packageService.setMd5AndVersion(soft_package_name);
			 logger.info("======打包完成======");
			 if((cmdFlag!=null&&cmdFlag.equalsIgnoreCase("1"))) {
			    String server_url=properties.getProperty("package.server.url");
				String upload_url=properties.getProperty("package.upload.url");
				String update_url=properties.getProperty("package.update.url");
				String login_url=properties.getProperty("package.login.url");
				String loginid=properties.getProperty("package.login.loginid");
				String psd=properties.getProperty("package.login.psd");
				//3、登录
				logger.info("======开始登录======");
				JSONObject login_json=HttpClientUtil.login(server_url+login_url, loginid, psd);
				if(login_json.getBoolean("state")==false) {
					throw new RuntimeException(login_json.getString("message")); 
				}
				logger.info("======开始上传文件======");
				//4、上传文件
				JSONObject upload_json=HttpClientUtil.upload(server_url+upload_url,package_path);
				if(upload_json.getBoolean("state")==false) {
					throw new RuntimeException(upload_json.getString("message")); 
				}
				logger.info("======开始开始进行升级======");
				//5、升级服务
				JSONObject update_json=HttpClientUtil.sendGetRequest(server_url+update_url);
				if(update_json.getInteger("status")==0) {
					throw new RuntimeException(update_json.getString("logs")); 
				}else {
					logger.info("======升级日志===>"+update_json.getString("logs"));
				}
				//最后关闭客户端
				HttpClientUtil.closeHttpClient();
				logger.info("======升级成功======");
		    }
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("======打包部署失败======"+e.getMessage());
		}
	}
}
